<template>
	<view class="container">
		<u-navbar leftText="组织信息" @leftClick="appFinish" leftIconColor="#1D2129" bgColor="transparent">
			<view class="u-nav-slot" slot="right">
				<view class="nav-left-text" @click="submitForm">
					保存
				</view>
			</view>
		</u-navbar>

		<view class="form_container">

			<u-form ref="form" labelPosition="left" :model="formData" labelWidth="auto" :labelStyle="labelStyle">
				<template>
					<u-form-item label="组织头像" prop="avatar" key="avatar" @click="showAvatarPop()">
						<!-- 				<u--input v-model="formData.avatar" placeholder="——" border="none" inputAlign="right">
						</u--input> -->
						<view class="avatar-form-item">
							<u-avatar class="avatar-box" :src="formData.avatar"></u-avatar>
						</view>
						<u-icon name="arrow-right" color="#cccccc" class="rightIcon"></u-icon>
					</u-form-item>
					<view class="divider"></view>
					<u-form-item label="组织名称" prop="name" key="name" class="custom_item"
						@click="showModalForm('修改组织名称', 'name')">
						<u--input v-model="formData.name" placeholder="-" readonly border="none" inputAlign="right">
						</u--input>
						<u-icon name="arrow-right" color="#cccccc" class="rightIcon"></u-icon>
					</u-form-item>
					<view class="divider"></view>
					<u-form-item label="邮箱" prop="email" key="email" class="custom_item"
						@click="showModalForm('修改邮箱', 'email')">
						<u--input v-model="formData.email" placeholder="-" readonly border="none" inputAlign="right">
						</u--input>
						<u-icon name="arrow-right" color="#cccccc" class="rightIcon"></u-icon>
					</u-form-item>
					<view class="divider"></view>
					<u-form-item label="地址" prop="address" key="address" class="custom_item"
						@click="showAddressPicker = true">
						<u--input v-model="addressName" placeholder="-" border="none" readonly inputAlign="right"
							class="custom_input">
						</u--input>
						<u-icon name="arrow-right" color="#cccccc" class="rightIcon"></u-icon>
					</u-form-item>
					<view class="divider"></view>
					<u-form-item label="行业" prop="industry" key="industry" class="custom_item"
						@click="showPop('选择行业', 'industry')">
						<u--input v-model="formData.industry" readonly placeholder="-" border="none" inputAlign="right">
						</u--input>
						<u-icon name="arrow-right" color="#cccccc" class="rightIcon"></u-icon>
					</u-form-item>

					<view class="divider"></view>
					<u-form-item label="类型" prop="type" key="type" class="custom_item" @click="showPop('选择类型', 'type')">
						<u--input v-model="formData.type" placeholder="-" readonly border="none" inputAlign="right">
						</u--input>
						<u-icon name="arrow-right" color="#cccccc" class="rightIcon"></u-icon>
					</u-form-item>

				</template>
			</u-form>

		</view>
		<view>


			<!-- 上传头像 -->
			<u-popup :show="isShowAvatarPop" round="10" @close="closeAvatarPop" mode="bottom">
				<view class="pop-container">
					<view class="avatar-pop-box">
						<view class="pop-item" @click="choosePic(1)">
							拍照
						</view>
						<view class="pop-item" @click="choosePic(2)">
							从手机相册选择
						</view>
					</view>
					<view class="pop-cancel-item" @click="closeAvatarPop">
						取消
					</view>
				</view>
			</u-popup>
			<!-- 编辑组织名称  邮箱  地址 -->
			<modalForm ref="modalFormRef" :isShowModal="isShowModal" :modalTitle="modalTitle" @closeModal="closeModal"
				@confirmModal="confirmModal"></modalForm>
			<!-- 编辑行业  类型 -->
			<popForm ref="popFormRef" :isShowPop="isShowPop" :popTitle="popTitle" @closePop="closePop"
				@confirmPop="confirmPop"></popForm>


			<u-picker :show="showAddressPicker" ref="uPicker" :defaultIndex="defaultAddress" :columns="addressColumns"
				@confirm="confirmPicker" @cancel="showAddressPicker = false" @change="changeHandler"
				keyName="label"></u-picker>

		</view>
		
		<view v-if="isShowAvatarPop" class="previewImg-box">
			<img mode="aspectFit" :src="formData.avatar" alt="" />
			<!-- <image :src="formData.avatar" mode="aspectFit"></image> -->
		</view>

	</view>
</template>

<script>
import {
	txCosUpload
} from '@/utils/txCosUpload'
import popForm from './components/popForm.vue'
import modalForm from './components/modalForm.vue'
import {
	regionData,
	CodeToText
} from './area-data-config';

export default {
	components: {
		popForm,
		modalForm
	},
	data() {
		return {
			isInit: false,
			initialFormData: {},
			isFormDataModified: false, // 标志位，记录表单是否被修改过
			value: [],
			areaArr: [],
			showAddressPicker: false,
			addressColumns: [],
			defaultAddress: [0, 0, 0],
			addressData: regionData,
			modalTitle: '',
			isShowModal: false,
			isShowNamePop: false,
			isShowAvatarPop: false,
			isShowPop: false,
			popTitle: '',
			labelStyle: {
				letterSpacing: '1px',
				marginLeft: '10px',
			},
			addressName: '', // 展示地址的名称
			formData: {
				// 头像
				avatar: '/static/image/avatar.png',
				// 昵称
				name: '',
				// 邮箱
				email: '',
				// 地址
				address: '',
				// 行业
				industry: '',
				// 类型
				type: '',
				phoneNum: ''
			},
			rules: {
				avatar: [{
					required: true,
					message: '请上传头像',
					trigger: 'blur'
				}],
				name: [{
					required: true,
					message: '请输入昵称',
					trigger: 'blur'
				}],
				phoneNum: [{
					required: true,
					message: '请输入手机号码',
					trigger: 'blur'
				}],
			},

		};
	},
	watch: {
		formData: {
			handler: function (newVal, oldVal) {
				this.isFormDataModified = this.isModified();
				if (this.isFormDataModified) {
					console.log('修改过啦')
				}
			},
			deep: true
		}
	},
	// onBackPress(options) {
	// 	if (options.from === 'navigateBack' && this.isFormDataModified) {
	// 		// 来自于导航条返回按钮或者系统返回按钮
	// 		uni.showModal({
	// 			title: '提示',
	// 			content: '您修改的内容暂未保存确认退出吗？',
	// 			success: function(res) {
	// 				if (res.confirm) {
	// 					// 用户点击确定
	// 					// 可以在这里进行返回操作
	// 					// 如果需要返回，则不需要额外操作，直接返回 true
	// 					// 如果不需要返回，则阻止默认行为并返回 false
	// 					return true;
	// 				} else if (res.cancel) {
	// 					// 用户点击取消
	// 					// 阻止默认行为，不执行返回
	// 					return false;
	// 				}
	// 			}
	// 		});
	// 		// 阻止默认返回行为，等待modal结果
	// 		return true;
	// 	}
	// 	// 其他返回方式不弹窗
	// 	return false;
	// },
	onLoad() {
		this.getOrganizationInfo()
		this.initAreaData()
	},
	onPullDownRefresh() {
		this.getOrganizationInfo()
	},
	onUnload() {

	},
	methods: {
		isModified() {
			return JSON.stringify(this.formData) !== JSON.stringify(this.initialFormData);
		},
		appFinish() {
			let that = this;
			if (that.isFormDataModified) {
				uni.showModal({
					title: '提示',
					content: '您修改的内容暂未保存确认退出吗？',
					success: function (res) {
						if (res.confirm) {
							// 用户点击确定
							// 可以在这里进行返回操作
							// 如果需要返回，则不需要额外操作，直接返回 true
							// 如果不需要返回，则阻止默认行为并返回 false
							that.$utils.appFinish(that)
							return true;
						} else if (res.cancel) {
							// 用户点击取消
							// 阻止默认行为，不执行返回
							return false;
						}
					}
				});
			} else {
				that.$utils.appFinish(that)
			}
		},
		initAreaData() {
			//省的数组
			const provinceData = regionData.map(e => {
				return {
					label: e.label,
					value: e.value
				} //这里可以直接return e.label  这里我是要用到code所以才用对象包起来的 下面的市 区 也一样
			})
			//市的数组
			const cityData = regionData.map(e => {
				const arr = []
				arr.push(
					e.children.map(c => {
						return {
							label: c.label,
							value: c.value
						}

					})
				)
				return arr
			})
			//区的数组
			const areaData = regionData.map(e => {
				const arr = []
				arr.push(
					e.children.map(c => {
						if (c.children) { // 兼容特别行政区，香港，澳门等
							return c.children.map(d => {
								return {
									label: d.label,
									value: d.value
								}
							})
						}
					})
				)
				return arr
			})
			const arr = [provinceData, cityData[0][0], areaData[0][0][0]]
			this.addressColumns = arr //将得到的3个数组 的第一个市的所有数据赋值 作为初始数据
		},
		changeHandler(e) {
			//分别表示选中的列 , 该列的第几个,选中的3列的第几个的数组,组件本身
			const {
				columnIndex,
				index,
				indexs,
				picker = this.$refs.uPicker
			} = e
			//如果改变的是第一列
			if (columnIndex === 0) {
				const children1 = this.addressData[index].children.map(e => {
					return {
						label: e.label,
						value: e.value
					}
				})
				//更换 第二列数据
				picker.setColumnValues(1, children1)
				// 适应特区只有两级的情况
				if (!this.addressData[index]?.children[indexs[1]]?.children) {
					return picker.setColumnValues(2, [])
				}
				const children2 = this.addressData[index]?.children[indexs[1]]?.children?.map(e => {
					return {
						label: e.label,
						value: e.value
					}
				})
				//更换 第三列数据
				picker.setColumnValues(2, children2)
			}
			//如果改变的是第二列
			if (columnIndex === 1) {
				// 适应特区只有两级的情况
				if (!this.addressData[indexs[0]]?.children[indexs[1]]?.children) {
					return picker.setColumnValues(2, [])
				}
				const children3 = this.addressData[indexs[0]]?.children[indexs[1]]?.children?.map(e => {
					return {
						label: e.label,
						value: e.value
					}
				})
				//更换 第三列数据
				picker.setColumnValues(2, children3)
			}
		},

		// 确认选中的数据
		confirmPicker(e) {
			// 适应特区只有两级的情况
			if (!e.value[2]) {
				this.addressName = `${e.value[0].label}-${e.value[1].label}`
				this.formData.address = `${e.value[0].value},${e.value[1].value}`
			} else {
				this.addressName = `${e.value[0].label}-${e.value[1].label}-${e.value[2].label}`
				this.formData.address = `${e.value[0].value},${e.value[1].value},${e.value[2].value}`
			}
			this.showAddressPicker = false
		},
		//已经知道了 '省，市，区'初始弹窗时默认选中改值
		backfill(item) {
			let temp = item.split(',')
			let index,
				index1,
				index2 = 0
			let name,
				name1,
				name2 = ''
			let arr,
				arr1,
				arr2 = []
			//匹配省市区对应每列的第几个
			this.addressData.forEach((item, i) => {
				if (item.value == temp[0]) {
					index = i
					name = item.label
					item.children.forEach((val, ind) => {
						if (val.value == temp[1]) {
							index1 = ind
							name1 = val.label
							if (val.children) { // 适应特区只有两级的情况
								val.children.forEach((e, n) => {
									if (e.value == temp[2]) {
										index2 = n
										name2 = e.label
									}
								})
							}
						}
					})
				}
			})
			arr = this.addressData.map(e => {
				return {
					label: e.label,
					value: e.value
				}
			})
			arr1 = this.addressData[index].children.map(e => {
				return {
					label: e.label,
					value: e.value
				}
			})
			// 适应特区只有两级的情况
			if (this.addressData[index].children[index1].children) {
				arr2 = this.addressData[index].children[index1].children.map(e => {
					return {
						label: e.label,
						value: e.value
					}
				})
			}
			// 适应特区只有两级的情况
			if (name2 == '' || arr2.length == 0) {
				//反推出3列的数组数据
				this.addressColumns = [arr, arr1]
				// 赋值给 默认初始选中 
				this.defaultAddress = [index, index1]
				// 默认展示的地址名称
				this.addressName = `${name}-${name1}`
				return
			}
			//反推出3列的数组数据
			this.addressColumns = [arr, arr1, arr2]
			// 赋值给 默认初始选中 
			this.defaultAddress = [index, index1, index2]
			// 默认展示的地址名称
			this.addressName = `${name}-${name1}-${name2}`
		},

		async getOrganizationInfo() {
			const params = {}
			const res = await this.$request(this.$Api.getOrganizationInfo, params, "get")
			if (res.data.code != 200) return
			console.log('res', res)
			const {
				logo,
				name,
				email,
				address,
				industry,
				industryType,
			} = res.data.data;
			this.formData.avatar = logo
			this.formData.name = name
			this.formData.email = email
			this.formData.address = address
			this.formData.industry = industry
			this.formData.type = industryType

			this.backfill(address)
			uni.stopPullDownRefresh()
			// 创建一个表单数据的副本用于比较
			this.initialFormData = JSON.parse(JSON.stringify(this.formData));
			this.isInit = true
		},
		goBack() {
			uni.navigateBack();
		},
		showModalForm(title, formItem) {
			console.log('title', title)
			this.isShowModal = true
			this.modalTitle = title
			this.$refs.modalFormRef.modalFormData[formItem] = this.formData[formItem]
			console.log('this.$refs.modalFormRef', this.$refs.modalFormRef)
		},
		closeModal() {
			this.isShowModal = false
			this.modalTitle = ''
		},

		confirmModal(params) {
			if (params.modalTitle == '修改组织名称') {
				this.formData.name = params.data
			} else if (params.modalTitle == '修改邮箱') {
				this.formData.email = params.data
			} else if (params.modalTitle == '修改地址') {
				this.formData.address = params.data
			}
			this.isShowModal = false
			console.log('confirmModal111', this.formData)
		},

		showAvatarPop() {
			console.log('showAvatarPop')
			this.isShowAvatarPop = true
		},
		closeAvatarPop() {
			this.isShowAvatarPop = false
		},

		showPop(title, formItem) {
			console.log('showPop')
			this.isShowPop = true
			this.popTitle = title
			this.$refs.popFormRef.selectedId = this.formData[formItem]
		},
		closePop() {
			this.isShowPop = false
		},
		confirmPop(params) {
			if (params.popTitle == '选择行业') {
				this.formData.industry = params.data
			} else if (params.popTitle == '选择类型') {
				this.formData.type = params.data
			}
			this.isShowPop = false
			console.log('confirmPop', this.formData)
		},
		// 上传图片
		choosePic(type) {
			const vm = this
			if (type == 1) {
				this.$utils.androidCamera(this)
			} else {
				this.$utils.androidAlbum(this)
			}
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: async (res1) => {
					const file = res1.tempFiles[0];
					const params = {
						scene: 'business_avatar'
					}
					txCosUpload(file, params, (progressData) => {
						// 实现进度条，目前没用到
						console.log(123, Math.round(progressData.percent * 100))
					},).then(res => {
						uni.showToast({
							title: '图片上传成功',
							icon: 'none',
							duration: 1500
						})
						vm.formData.avatar = res.fileUrl
						this.isShowAvatarPop = false
					})
				}
			});
		},


		async submitForm() {
			console.log('submitForm');
			let orgId = await this.$utils.getOrgId(this)

			const params = {
				logo: this.formData.avatar,
				name: this.formData.name,
				email: this.formData.email,
				address: this.formData.address + ',',
				industry: this.formData.industry,
				industryType: this.formData.type,
				orgId: orgId,
				miniProgram: '',
				officialAccount: '',
				serialNumber: '',
				desc: '',
			}

			const res = await this.$request(this.$Api.updateOrganizationInfo, params, "post")
			if (res.data.code != 200) return
			this.isFormDataModified = false
			uni.showToast({
				title: '更改成功',
				icon: 'none',
			});
		},

		async updateOrganizationInfo() {
			console.log('updateOrganizationInfo')
			const params = {
				logo: this.formData.avatar,
				name: this.formData.name,
				email: this.formData.email,
				address: this.formData.address,
				industry: this.formData.industry,
				industryType: this.formData.type,
			}

			const res = await this.$request(this.$Api.updateOrganizationInfo, params, "post")

			uni.showToast({
				title: '更改成功',
				icon: 'none',
			});
		}

	}
};
</script>

<style lang="scss" scoped>
.container {
	position: relative;
	height: 100vh;
	overflow-y: hidden;
	overflow: hidden;
	background: url('@/static/image/my_set_bg.png') no-repeat center center;
	background-size: cover;
	background-color: #fafbff;

	::v-deep .u-navbar__content__left__text {
		font-weight: 500;
		font-size: 32rpx;
	}

	.avatar-form-item {
		width: 100%;
		display: flex;
		justify-content: flex-end;
		float: right;
	}

	.avatar-box {
		width: 80rpx;
		height: 80rpx;
	}

	.pop-container {
		font-size: 34rpx;
		color: #000000;
		text-align: center;
		background-color: #F2F2F2;

		.pop-item {
			padding: 32rpx 0;
			background-color: #FFFFFF;
			margin-bottom: 2rpx;
		}

		.pop-cancel-item {
			background-color: #FFFFFF;
			padding: 32rpx 0;
			margin-top: 16rpx;
		}
	}

	.form_container {
		background-color: #fafbff;
		height: 100vh;
		margin: 32rpx;
		margin-top: 96rpx;
		border-radius: 16rpx;

		// padding-top: 32rpx;
		.custom_input {
			pointer-events: none;
		}

		.notice_container {
			height: 160rpx;
			margin: 0 28rpx;
			padding: 20rpx;
			background: #F7FAFF;
			border-radius: 14rpx;

			.status {
				font-weight: 500;
				font-size: 28rpx;
				color: #00C795;
			}

			.note {
				font-weight: 400;
				font-size: 24rpx;
				color: #8C8C8C;
			}

			.contact {
				font-weight: 400;
				font-size: 24rpx;
				color: #295FFF;
			}
		}

		.divider {
			border-bottom: 1rpx solid #E3E8EE;
			margin: 30rpx 0;
		}

		.u-form {
			padding: 40rpx;
			// height: 100vh;
			border-radius: 16rpx;
			background-color: #ffffff;

			::v-deep .u-form-item__body {
				padding: 10rpx 0;
			}

			::v-deep .u-form-item__body__left__content__required {
				left: -1px;
			}
		}


	}

	.custom_btn {
		display: flex;
		justify-content: center;
		align-items: center;
		width: fit-content;
		padding: 14rpx 32rpx;
		text-align: center;
		border: 2rpx solid #295EFF;
		border-radius: 8rpx;
		color: #295EFF;
		font-size: 28rpx;
		font-weight: 400;

		image {
			width: 24rpx;
			height: 24rpx;
			margin-right: 12rpx;
		}
	}

	.nav-left-text {
		color: #295FFF;
	}

	.slot-content {
		padding: 34rpx 0;
		width: 100%;
	}
	
	.previewImg-box {
		position: fixed;
		z-index: 999999;
		top: 40%;
		left: 50%;
		transform: translate(-50%,-50%);
	}

	.name-input {}

}
</style>